<template>
    <div class="vue-ms-main  vue-ms-main-add" v-loading="loading">
        <div class="ms-top">
            <!-- 当前页标题  -->
            <div class="crumbs fl">
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item><i class="el-icon-menu"></i><a @click="$router.push('/proAll')">  项目列表</a> </el-breadcrumb-item>
                    <el-breadcrumb-item v-if="ruleForm.id != 0">项目编辑</el-breadcrumb-item>
                    <el-breadcrumb-item v-if="ruleForm.id == 0">项目添加</el-breadcrumb-item>
                    <el-button v-if="ruleForm.id != 0" type="primary" plain style="float: right" @click="addBtn()">添加项目</el-button>
                </el-breadcrumb>
            </div>
        </div>
        <!--  添加 -->
        <div class = "ms-updmain">
            <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <div class="info infos">
                    <div class="fl upd-model" prop="userName">
                        <el-form-item label="项目名称" prop="projectName" ><i class="xing">*</i>
                            <el-input type="text" v-model="ruleForm.projectName"  :rules="[{ required: true},]" placeholder="请填写项目名称" auto-complete="on"></el-input>
                        </el-form-item>
                        <el-form-item label="负责人员" ><i class="xing">*</i>
                            <el-select v-model="ruleForm.owner_id" filterable placeholder="请选择"><i class="xing">*</i>
                                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="测试人员" ><i class="xing">*</i>
                            <el-select v-model="ruleForm.tester" filterable placeholder="请选择">
                                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item v-if="ruleForm.id == 0" label="项目进度" :rules="[{ required: true, message: '请输入项目进度'}]" prop="progress"><i class="xing">*</i>
                            <!--<el-slider style="margin-left: 6px;" v-model="ruleForm.progress" show-input></el-slider>-->
                            <el-input type="number" v-model="ruleForm.progress"  placeholder="请填写项目进度" auto-complete="on"></el-input>
                        </el-form-item>
                        <el-form-item v-if="ruleForm.id != 0" label="项目进度" :rules="[{ required: true, message: '请输入项目进度'}]" prop="progress"><i class="xing">*</i>
                            <el-input type="number" :disabled="true" v-model="ruleForm.progress"  placeholder="请填写项目进度" auto-complete="on"></el-input>
                        </el-form-item>
                        <el-form-item label="优先级别" :rules="[{ required: true, message: '请输入项目进度'}]"><i class="xing">*</i>
                            <el-select v-model="ruleForm.priority" filterable placeholder="请选择">
                                <el-option v-for="item in priorityList" :key="item.value" :label="item.lable" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div class="fr upd-model">
                        <el-form-item label="开始时间" prop="start_date"><i class="xing">*</i>
                            <el-date-picker v-model="ruleForm.start_date"  align="right" type="datetime"  placeholder="选择日期" :picker-options="pickerOptions1"></el-date-picker>
                        </el-form-item>
                        <el-form-item label="结束时间" prop="end_date" ><i class="xing">*</i>
                            <el-date-picker v-model="ruleForm.end_date" align="right" type="datetime"  placeholder="选择日期" :picker-options="pickerOptions1"></el-date-picker>
                        </el-form-item>
                        <el-form-item v-if="ruleForm.id == 0" label="持续时间" :rules="[{ required: true, message: '请输入持续时间'}]" prop="duration" ><i class="xing">*</i>
                            <el-input type="number" v-model="ruleForm.duration"  placeholder="请填写持续时间" auto-complete="on"></el-input>
                        </el-form-item>
                        <el-form-item v-if="ruleForm.id != 0" label="持续时间" :rules="[{ required: true, message: '请输入持续时间'}]" prop="duration" ><i class="xing">*</i>
                            <el-input :disabled="true" type="number" v-model="ruleForm.duration"  placeholder="请填写持续时间" auto-complete="on"></el-input>
                        </el-form-item>
                        <el-form-item label="归属地点" prop="Location"><i class="xing">*</i>
                            <el-input type="text" v-model="ruleForm.Location" placeholder="请填写归属地点" auto-complete="off"></el-input>
                        </el-form-item>
                    </div>
                </div>
                <div class="info infos">
                    <el-form-item label=" 关联 url ">
                        <el-input type="text" v-model="ruleForm.hookURL"  placeholder="请填写钉钉项目群 群机器人的webhook,默认国朗研发部任务通知" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="项目描述" prop="text" ><i class="xing">*</i>
                        <el-input type="textarea" v-model="ruleForm.text" rows="8" placeholder="请填写项目描述" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item v-if="isCz || noLoginUser === 79">
                        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                        <el-button @click="resetForm('ruleForm')">重置</el-button>
                    </el-form-item>
                </div>
            </el-form>
        </div>

    </div>
</template>

<script>
    import insurance from '../../api/insurance';
    export default {
        data() {
            var checkProName = (rule, value, callback) => {if (!value) { return callback(new Error('请输入项目名称'));}else{callback(); }};
            var checkProDescription = (rule, value, callback) => { if (!value) {return callback(new Error('请填写项目描述'));}else{callback();} };
            var checkProAttribution = (rule, value, callback) => {if (!value) {return callback(new Error('请输入项目归属地点'));}else{callback();}};
            var checkStartDate = (rule, value, callback) => {if (!value) { return callback(new Error('请选择开始时间'));}else{callback(); }};
            var checkEndDate = (rule, value, callback) => {
                if (!value) { return callback(new Error('请选择结束时间'));}else{callback(); }
            };
            var checkDuration = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('请填写持续时间'));
                }else{
                    callback();
                }
            };
            var checkProgress = (rule, value, callback) => {if (!value) { return callback(new Error('请填写项目进度'));}else{callback(); }};
            var checkHookURL = (rule, value, callback) => {if (!value) { return callback(new Error('请填写钉钉项目群 群机器人的webhook'));}else{callback(); }};

            return {
                isCz:true,
                noLoginUser:0,
                options: [],
                paramsId:'',
                paramsRouter:'proAll',
                ruleForm: {
                    id:0,
                    projectName: "",    //项目名称
                    text:'',            // 项目描述
                    Location:"",        // 所属城市
                    start_date: "", // 开始时间
                    end_date: "",   // 结束时间
                    duration: 0,   //  持续时间
                    progress: 0,  // 进度
                    owner_id: 32,  // 所属者
                    parent: 0,      // 归属哪个模块
                    priority:3,     //  优先级
                    hookURL:'',     // 关联url
                    tester:66,      // 测试人员
                    creator:66,     // 创建人员
                    operator:66    // 操作员
                },
                // 验证
                rules: {
                    projectName: [
                        { validator: checkProName, trigger: 'blur' }
                    ],
                    text: [
                        { validator: checkProDescription, trigger: 'blur' }
                    ],
                    Location: [
                        { validator: checkProAttribution, trigger: 'blur' }
                    ],
                    start_date: [
                        { validator: checkStartDate, trigger: 'blur' }
                    ],
                    end_date: [
                        { validator: checkEndDate, trigger: 'blur' }
                    ],
                    duration: [
                        { validator: checkDuration, trigger: 'blur' }
                    ],
                    progress: [
                        { validator: checkProgress, trigger: 'blur' }
                    ],
                    hookURL: [
                        { validator: checkHookURL, trigger: 'blur' }
                    ],
                },
                loading:false,
                priorityList:[{'value':1,'lable':'一级'},{'value':2,'lable':'二级'},{'value':3,'lable':'三级'},],
                pickerOptions1: {
                    shortcuts: [{
                        text: '今天',
                        onClick(picker) {
                            picker.$emit('pick', new Date());
                        }
                    }, {
                        text: '昨天',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24);
                            picker.$emit('pick', date);
                        }
                    }, {
                        text: '一周前',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', date);
                        }
                    }]
                },
            };
        },
        watch: {
            '$route': 'getParams'
        },
        methods: {
            submitForm(formName) {
                var that = this;

                if(that.paramsRouter == undefined){
                    that.paramsRouter = 'proAll';
                }
                that.$refs[formName].validate((valid) => {
                    if (valid) {
                        that.addLoading = true;
                        let para = Object.assign({}, that.ruleForm);
                        if(parseFloat(para.progress)>1){
                            para.progress = 1;
                        }
                        if(para.hookURL == ''){
                            // para.hookURL = 'https://oapi.dingtalk.com/robot/send?access_token=cf8e62030685637f33e614b77b6156c93903feeb1d73833a93bf9d0ff1bf34ac'; // 测试群
                            para.hookURL = 'https://oapi.dingtalk.com/robot/send?access_token=bd78cea6877351342291b3a5995953d61ca1de366e8dfce74c92ca1ce568424e';    // 国朗群
                        }
                        var start = new Date(that.ruleForm.start_date);
                        var end = new Date(that.ruleForm.end_date);
                        if((end - start) < 0){
                            that.altopen('时间错误！','warning');
                        }else{
                            var duration = Math.floor((end-start)/(24*3600*1000))*24;
                            para.progress =  (Math.round(parseFloat(para.progress) * 100))/100;
                            var data =JSON.stringify({
                                "ID": parseInt(para.id),
                                "projectName":para.projectName,
                                "text":para.text,
                                "Location":para.Location,
                                "type":'0',
                                "start_date":this.formatData(para.start_date),
                                "end_date":this.formatData(para.end_date),
                                "duration":parseInt(para.duration),
                                "progress":(that.ruleForm.progress/100).toString(),
                                "owner_id":parseInt(para.owner_id),
                                "parent":parseInt(para.parent),
                                "hookURL":para.hookURL,     // 关联url
                                "priority":parseInt(para.priority),
                                "tester":parseInt(para.tester),     // 测试人员
                                "creator":parseInt(para.creator),   // 创建人员
                                "operator":parseInt(JSON.parse(sessionStorage.getItem('user')).id)  // 登录人员
                            });
                            $.ajax(insurance.posturl+"proj/StorgeProj",{
                                'data': data,
                                headers: {'Content-Type': 'application/json;charset=UTF-8'},
                                'type': 'POST',
                                success:function (res) {
                                    res = JSON.parse(res);
                                    if(res.isSuccess === false){
                                        if(para.id == 0){
                                            that.altopen('添加'+res.msg,'success');
                                        }else{
                                            that.altopen('修改'+res.msg,'success');
                                        }
                                    }else{
                                        if(para.id == 0){
                                            that.altopen('添加'+res.msg,'success');
                                        }else{
                                            that.altopen('修改'+res.msg,'success');
                                        }
                                        that.addFormVisible = false;
                                        that.$router.push({ path: '/'+that.paramsRouter});
                                    }
                                    that.addLoading = false;
                                }
                            });
                            // this.loading = true;
                        }
                    } else {
                        this.altopen('请把信息填写完整！','warning');
                        return false;
                    }
                });
            },
            resetForm(formName) {
                this.initDay();
                // this.$refs[formName].resetFields();
            },
            // 公共弹框
            altopen(msg,type) {
                this.$notify({
                    type:type,
                    message: msg,
                    offset: 100,
                });
            },
            // 添加按钮
            addBtn(){
                this.isCz = true;
                var t = new Date;
                this.ruleForm = {
                    "id":0,
                    "projectName":'',
                    "text":'',
                    "Location":'',
                    "type":'0',
                    "start_date":new Date(t.getFullYear(), t.getMonth(), t.getDate(), '09', '00'),
                    "end_date":new Date(t.getFullYear(), t.getMonth(), t.getDate(), '17', '30'),
                    "duration":0,
                    "progress":0,
                    "owner_id":32,
                    "parent":'0',
                    "hookURL":'',     // 关联url
                    "priority":3,
                    "tester":66,     // 测试人员
                    "creator":parseInt(JSON.parse(sessionStorage.getItem('user')).id),  // 创建人员，第一次添加为当前登录人员，之后的子项目添加或修改 都为这个人
                    "operator":parseInt(JSON.parse(sessionStorage.getItem('user')).id)  // 登录人员
                };
            },
            // 修改页面传值
            getProList () {
                this.paramsId = this.$route.query.ID;
                this.paramsRouter = this.$route.query.routers;
                var that = this;
                if(that.paramsId != undefined && that.paramsId  > 0){
                    that.loading = true;
                    $.ajax(insurance.posturl+"proj/projInfo?projID="+that.paramsId,{
                        headers: {'Content-Type': 'application/json;charset=UTF-8'},
                        'type': 'GET',
                        success:function (res) {
                            res = JSON.parse(JSON.parse(res).Content)[0];
                            var data = {
                                "id": res.ID,
                                "projectName":res.projectName,
                                "text":res.text,
                                "Location":res.Location,
                                "type":'0',
                                "start_date":that.dateR(res.start_date),
                                "end_date":that.dateR(res.end_date),
                                "duration":res.duration,
                                "progress":parseFloat(parseFloat(res.progress)*100),
                                "owner_id":res.owner_id,
                                "parent":res.parent,
                                "hookURL":res.hookURL,     // 关联url
                                "priority":res.priority,
                                "tester":res.tester,
                                "creator":res.creator,
                                "operator":res.operator
                            };
                            if(JSON.parse(sessionStorage.getItem('user')).id != res.owner_id){
                                that.isCz = false;
                            }else{
                                that.isCz = true;
                            }
                             that.ruleForm = data;
                            that.loading = false;
                        }
                    });
                }else{
                 that.addBtn();
                }
            },
            getUser(){
                var that = this;
                $.ajax(insurance.posturl+"user/AllUsers?page=0&pageSize=200",{
                    headers: {'Content-Type': 'application/json;charset=UTF-8'},
                    'type': 'GET',
                    success:function (res) {
                        res = JSON.parse(JSON.parse(res).Content);
                        var datas = [];
                        for(var i = 0; i<res.list.length; i++){
                            datas.push({'value':res.list[i].id,'label':res.list[i].name});
                        }
                        that.options = datas;
                    }
                });
            },
            // 日 - 月
            dateR(d){
                var dates = d.split('-');
                return dates[1] + '-' + dates[0] + '-' + dates[2];
            },
            formatData(d){
                var d1 = new Date();
                if(d != undefined){
                    d1 = new Date(d);
                }
                var m = d1.getMonth()+1;
                var d = d1.getDate();
                if((m+'').length <= 1){
                    m = '0'+m;
                }
                if((d+'').length <= 1){
                    d = '0'+d1.getDate();
                }
                return d+ '-' + m + '-' + d1.getFullYear() + ' ' + d1.getHours() + ':' + d1.getMinutes();
            },
            // 初始化数据
            initDay(){
                var t = new Date;
                this.ruleForm.start_date = new Date(t.getFullYear(), t.getMonth(), t.getDate(), '09', '00');
                this.ruleForm.end_date = new Date(t.getFullYear(), t.getMonth()+1, t.getDate(), '17', '30');
                this.getUser(); //  用户列表
                this.getProList();// 修改页面接受值
                this.noLoginUser = JSON.parse(sessionStorage.getItem('user')).id;
            },
        },

        mounted(){
            this.initDay();
        },
        created(){
            this.initDay();
        }
    }
</script>
<style>
    .el-form-item__content{position: relative};

    .xing{color: red; font-size: 20px; position: absolute;left: -75px; top: 7px;}
    .img-upd-div{height: 134px; width: 225px; float:left; overflow: hidden;border: #ccc 1px solid;margin-bottom: 5px; margin-right: 5px; position: relative}
    .img-upd-div .el-form-item__error{ position: absolute; bottom: 0px;  text-align: center; left: 0px; width: 100%;}
    .image-list2 .img-uplod{
        position: absolute;
        z-index: 999;
        background: transparent;
        top: -24px;
        width: 100%;
        height: 160px !important;
        color: #fff;
    }

</style>
